//
//  AppDelegate.m
//  BeidouMall
//
//  Created by qie on 16/3/28.
//  Copyright © 2016年 qie. All rights reserved.
//

#import "AppDelegate.h"
#import "BDPoint.h"
#import "BDLineSegment.h"
#import <AVFoundation/AVFoundation.h>

#define PI 3.1415926
#define MyINFINITY 0.00000000001
#define ESP 0.000001

@interface AppDelegate () <BMKLocationServiceDelegate,WXApiDelegate>
{
    BMKMapManager* _mapManager;
    BMKLocationService *_locService;
    NSTimer *_timer;
    
    AVAudioPlayer *_audioplayer;
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    [self playStartUpMusic];
    
    [NSThread sleepForTimeInterval:1.5];
    // 百度地图注册
    [self baiduMapSetting];
    // 向微信注册wxf60253933427cdd6
    [WXApi registerApp:@"wxf60253933427cdd6" withDescription:@"demo 2.0"];
    // 设置状态栏样式 白色字
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];//UIStatusBarStyleDefault
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // 进入后台时销毁定位计时
    [_timer invalidate];
    _timer = nil;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    // 进入前台时创建定位计时
    [self startLocation];
     _timer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(startLocation) userInfo:nil repeats:YES];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    //如果极简开发包不可用，会跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给开发包
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"result = %@",resultDic);
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"result = %@",resultDic);
        }];
    }
    if ([url.host isEqualToString:@"pay"]) {
        // 处理微信通过URL启动App时传递的数据
        return  [WXApi handleOpenURL:url delegate:self];
    }
    
    return YES;
}
// 处理微信通过URL启动App时传递的数据
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:self];
}

// 微信支付成功或者失败回调
-(void) onResp:(BaseResp*)resp {
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;
    
    if([resp isKindOfClass:[SendMessageToWXResp class]]) {
        strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    if([resp isKindOfClass:[PayResp class]]) {
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                break;
        }
    }
    //创建一个消息对象
    NSNotification * notice = [NSNotification notificationWithName:@"weixinPay" object:nil userInfo:@{@"errCode":@(resp.errCode)}];
    //发送消息
    [[NSNotificationCenter defaultCenter]postNotification:notice];
}

#pragma mark BMKLocationServiceDelegate

//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation {
    //NSLog(@"heading is %@",userLocation.heading);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [BDAccountManagerModel shareInstance].latitude = userLocation.location.coordinate.latitude;
    [BDAccountManagerModel shareInstance].longitude = userLocation.location.coordinate.longitude;
}

- (void)didFailToLocateUserWithError:(NSError *)error {
    [BDAccountManagerModel shareInstance].inBoundary = @"fail";
}

- (void)geoCoding {// 经纬度反查地理位置信息
    NSString *urlStr = [NSString stringWithFormat:@"http://api.map.baidu.com/geocoder/v2/?ak=Sxu7ULwGKHYFTmsyyNR3GlGwxrBnQEcK&callback=renderReverse&location=%f,%f&output=json&pois=0&mcode=com.doudou.BeidouMall",[BDAccountManagerModel shareInstance].latitude,[BDAccountManagerModel shareInstance].longitude];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod = @"GET";
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"error = %@",[error localizedDescription]);
        } else {
            NSObject *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"json = %@",json);
            NSString *jsonStr = (NSString *)json;
            NSArray *arr = [jsonStr componentsSeparatedByString:@"("];
            jsonStr = arr[1];
            arr = [jsonStr componentsSeparatedByString:@")"];
            jsonStr = arr[0];
            NSDictionary *dic = [NSString dictionaryWithJsonString:jsonStr];
            if ([dic valueForKey:@"result"]) {
                dic = dic[@"result"];
                NSInteger cityCode = [[dic valueForKey:@"cityCode"] integerValue];
                [BDAccountManagerModel shareInstance].cityCode = cityCode;
            }
        }
    }];
    [task resume];
}

#pragma mark Private method

- (double)lantitudeLongitudeDist:(double)lon1 other_Lat:(double)lat1 self_Lon:(double)lon2 self_Lat:(double)lat2 {
    double er = 6378137; // 6378700.0f;
    //ave. radius = 6371.315 (someone said more accurate is 6366.707)
    //equatorial radius = 6378.388
    //nautical mile = 1.15078
    double radlat1 = PI*lat1/180.0f;
    double radlat2 = PI*lat2/180.0f;
    //now long.
    double radlong1 = PI*lon1/180.0f;
    double radlong2 = PI*lon2/180.0f;
    if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south
    if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north
    if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west
    if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south
    if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north
    if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west
    //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
    //zero ag is up so reverse lat
    double x1 = er * cos(radlong1) * sin(radlat1);
    double y1 = er * sin(radlong1) * sin(radlat1);
    double z1 = er * cos(radlat1);
    double x2 = er * cos(radlong2) * sin(radlat2);
    double y2 = er * sin(radlong2) * sin(radlat2);
    double z2 = er * cos(radlat2);
    double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
    //side, side, side, law of cosines and arccos
    double theta = acos((er*er+er*er-d*d)/(2*er*er));
    double dist  = theta*er;
    return dist;
}

- (double)maxWithX:(double)x Y:(double)y {
    return x >= y ? x : y;
}

- (double)minWithX:(double)x Y:(double)y {
    return x >= y ? y : x;
}

- (double)MultiplyWithPoint1:(BDPoint *)p1 Point2:(BDPoint *)p2 Point0:(BDPoint *)p0 {
    return ( (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y) );
}

- (BOOL)IsOnlineWithPoint:(BDPoint *)point LineSegment:(BDLineSegment *)line {
    
    return( (fabs([self MultiplyWithPoint1:line.pt1 Point2:line.pt2 Point0:point]) < ESP ) &&
           
           ( ( point.x - line.pt1.x ) * ( point.x - line.pt2.x ) <= 0 ) &&
           
           ( ( point.y - line.pt1.y ) * ( point.y - line.pt2.y ) <= 0 ) );
}

- (BOOL)IntersectWithLineSegment1:(BDLineSegment *)L1 LineSegment2:(BDLineSegment *)L2 {
    return( ([self maxWithX:L1.pt1.x Y:L1.pt2.x] >= [self minWithX:L2.pt1.x Y:L2.pt2.x]) &&
           
           ([self maxWithX:L2.pt1.x Y:L2.pt2.x] >= [self minWithX:L1.pt1.x Y:L1.pt2.x]) &&
           
           ([self maxWithX:L1.pt1.x Y:L1.pt2.x] >= [self minWithX:L2.pt1.x Y:L2.pt2.x]) &&
           
           ([self maxWithX:L2.pt1.x Y:L2.pt2.x] >= [self minWithX:L1.pt1.x Y:L1.pt2.x]) &&
           
           ([self MultiplyWithPoint1:L2.pt1 Point2: L1.pt2 Point0:L1.pt1] * [self MultiplyWithPoint1:L1.pt2 Point2: L2.pt2 Point0:L1.pt1] >= 0) &&
           
           ([self MultiplyWithPoint1:L1.pt1 Point2: L2.pt2 Point0:L2.pt1] * [self MultiplyWithPoint1:L2.pt2 Point2: L1.pt2 Point0:L2.pt1] >= 0)
           
           );
}

/* 射线法判断点q与多边形polygon的位置关系，要求polygon为简单多边形，顶点逆时针排列
 如果点在多边形内： 返回0
 如果点在多边形边上： 返回1
 如果点在多边形外： 返回2
*/
- (int)InPolygonWithList:(NSArray *)polygon Point:(BDPoint *)point {
    NSInteger n = polygon.count;
    int count = 0;
    BDLineSegment *line = [[BDLineSegment alloc] init];
    line.pt1 = point;
    line.pt2.y = point.y;
    line.pt2.x = - MyINFINITY;
    for( int i = 0; i < n; i++) {
        BDLineSegment *side = [[BDLineSegment alloc] init];
        side.pt1 = polygon[i];
        side.pt2 = polygon[(i + 1) % n];
        if ([self IsOnlineWithPoint:point LineSegment:side]) {
            return 1;
        }
        if (fabs(side.pt1.y - side.pt2.y) < ESP) {
            continue;
        }
        if ([self IsOnlineWithPoint:side.pt1 LineSegment:line]) {
            if( side.pt1.y > side.pt2.y ) {
                count++;
            }
        } else if ([self IsOnlineWithPoint:side.pt2 LineSegment:line]) {
            if( side.pt2.y > side.pt1.y ) {
                count++;
            }
        } else if ([self IntersectWithLineSegment1:line LineSegment2:side]) {
            count++;
        }
    }
    return  count % 2 == 1 ? 0 : 2;
}

- (void)startLocation {
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
        NSLog(@"定位功能不可用，提示用户或忽略");
        [BDAccountManagerModel shareInstance].inBoundary = @"fail";
        return;
    } else {
        [BDAccountManagerModel shareInstance].inBoundary = @"doing";
    }
    //启动LocationService
    [_locService startUserLocationService];
    //2秒后停止位置更新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_locService stopUserLocationService];
        BDPoint *point1 = [[BDPoint alloc] initWithX:30.0678260000 andY:101.9679900000];
        BDPoint *point2 = [[BDPoint alloc] initWithX:30.0678260000 andY:101.9719420000];
        BDPoint *point3 = [[BDPoint alloc] initWithX:30.0654500000 andY:101.9792000000];
        BDPoint *point4 = [[BDPoint alloc] initWithX:30.0648250000 andY:101.9878240000];
        BDPoint *point5 = [[BDPoint alloc] initWithX:30.0614490000 andY:101.9930700000];
        
        BDPoint *point6 = [[BDPoint alloc] initWithX:30.0558230000 andY:101.9934300000];
        BDPoint *point7 = [[BDPoint alloc] initWithX:30.0525720000 andY:101.9868900000];
        BDPoint *point8 = [[BDPoint alloc] initWithX:30.0477580000 andY:101.9797030000];
        BDPoint *point9 = [[BDPoint alloc] initWithX:30.0141140000 andY:101.9804940000];
        BDPoint *point10 = [[BDPoint alloc] initWithX:30.0061080000 andY:101.9797030000];
        
        BDPoint *point11 = [[BDPoint alloc] initWithX:29.9976000000 andY:101.9781220000];
        BDPoint *point12 = [[BDPoint alloc] initWithX:29.9901560000 andY:101.9725890000];
        BDPoint *point13 = [[BDPoint alloc] initWithX:29.9861520000 andY:101.9622400000];
        BDPoint *point14 = [[BDPoint alloc] initWithX:29.9874030000 andY:101.9562760000];
        BDPoint *point15 = [[BDPoint alloc] initWithX:29.9919080000 andY:101.9513170000];
        
        BDPoint *point16 = [[BDPoint alloc] initWithX:29.9978510000 andY:101.9493050000];
        BDPoint *point17 = [[BDPoint alloc] initWithX:30.0040430000 andY:101.9502390000];
        BDPoint *point18 = [[BDPoint alloc] initWithX:30.0114870000 andY:101.9533290000];
        BDPoint *point19 = [[BDPoint alloc] initWithX:30.0196180000 andY:101.9538320000];
        BDPoint *point20 = [[BDPoint alloc] initWithX:30.0299370000 andY:101.9570660000];
        
        BDPoint *point21 = [[BDPoint alloc] initWithX:30.0377530000 andY:101.9585750000];
        BDPoint *point22 = [[BDPoint alloc] initWithX:30.0455690000 andY:101.9541200000];
        BDPoint *point23 = [[BDPoint alloc] initWithX:30.0546350000 andY:101.9562040000];
        BDPoint *point24 = [[BDPoint alloc] initWithX:30.0609490000 andY:101.9604440000];
        BDPoint *point25 = [[BDPoint alloc] initWithX:30.0681380000 andY:101.9615220000];
        
        NSArray *polygon = @[point1,point2,point3,point4,point5,
                             point6,point7,point8,point9,point10,
                             point11,point12,point13,point14,point15,
                             point16,point17,point18,point19,point20,
                             point21,point22,point23,point24,point25];
        if ([self InPolygonWithList:polygon Point:
             [[BDPoint alloc] initWithX:[BDAccountManagerModel shareInstance].latitude
                                   andY:[BDAccountManagerModel shareInstance].longitude]] == 2) {
                 [BDAccountManagerModel shareInstance].inBoundary = @"no";
             } else {
                 [BDAccountManagerModel shareInstance].inBoundary = @"yes";
             }
                [BDAccountManagerModel shareInstance].inBoundary = @"yes";
    });
}

- (void)playStartUpMusic {// 播放启动音效
    // 1.音频文件的url路径,换成wav格式没声音
    NSString *string = [[NSBundle mainBundle] pathForResource:@"gogoBeidou" ofType:@"mp3"];
    NSURL *soundUrl = [NSURL fileURLWithPath:string];
    //2.创建播放器（注意：一个AVAudioPlayer只能播放一个url）
    NSError *error = nil;
    _audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&error];
    _audioplayer.numberOfLoops = 0;
    [_audioplayer prepareToPlay];
    if (error) {
        NSLog(@"创建播放器过程中发生错误，错误信息：%@",error.localizedDescription);
    }
    //4.播放
    [_audioplayer play];
}

- (void)baiduMapSetting {
    //请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定generalDelegate参数
    BOOL ret = [_mapManager start:Map_ak  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc] init];
    _locService.delegate = self;
}


@end
